package com.atldy.commerce.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @Author: lidongyang
 * @CreateTime: 2021-08-07 11:11
 * @Description： 自定义局部过滤器 校验token 的 filter 局部过虑器
 * // TODO: 2021/8/7  全局过滤器需要实现GlobalFilter 、局部实现 GatewayFilter
 */
@Slf4j
public class HeaderTokenGatewayFilter implements GatewayFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("token");
        log.info("从请求中获取:[{}]" , token);
        //判断是否包含
        if (StrUtil.equals(token, "imooc")) {
            return chain.filter(exchange);
        }
        //如果不包含，则直接返回
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 2;
    }
}